<script setup lang="ts">
import { Chat } from '@ai-sdk/vue'
import type { UIMessage } from 'ai'
import { getTextFromMessage } from '@nuxt/ui/utils/ai'
import { DefaultChatTransport } from 'ai'
import { ref } from 'vue'

const config = useRuntimeConfig()
const serverUrl = config.public.serverURL

const messages: UIMessage[] = []
const input = ref('')

const chat = new Chat({
  messages,
  transport: new DefaultChatTransport({
    api: `${serverUrl}/ai`,
  }),
  onError(error) {
    console.error('Chat error:', error)
  }
})

async function handleSubmit(e: Event) {
  e.preventDefault()
  const userInput = input.value
  input.value = ''
  
  if (!userInput.trim()) return
  
  chat.sendMessage({ text: userInput })
}
</script>

<template>
  <div class="grid grid-rows-[1fr_auto] w-full h-full mx-auto p-4">
    <UChatMessages :messages="chat.messages" :status="chat.status">
      <template #content="{ message }">
        <div class="whitespace-pre-wrap">\{{ getTextFromMessage(message) }}</div>
      </template>
    </UChatMessages>
    <UChatPrompt 
      v-model="input" 
      :error="chat.error" 
      @submit="handleSubmit" 
      placeholder="Type your message..."
      class="w-full"
    >
      <UChatPromptSubmit 
        :status="chat.status" 
        @stop="chat.stop" 
        @reload="chat.regenerate" 
      />
    </UChatPrompt>
  </div>
</template>